﻿using System;
using System.Collections.Generic;
using System.Linq;
using CH.FourBoards.LagerWalti.Persistence.DataAccess.EntityProviders;
using CH.FourBoards.LagerWalti.Persistence.Entities;

namespace CH.FourBoards.LagerWalti.Persistence.DataAccess
{
    public class PersistenceManager : IDisposable
    {
        private readonly DataContext _context;

        public PersistenceManager()
        {
            _context = new DataContext();
        }

        #region CRUD Operations

        public T Select<T>(int id) where T : IEntity
        {
            var manager = new EntityProviderFactory(_context).GetForType<T>();
            return (T) manager.Select(id);
        }

        public IEnumerable<T> SelectAll<T>(bool eagerlyLoading = false) where T : IEntity
        {
            var manager = new EntityProviderFactory(_context).GetForType<T>();
            return (IEnumerable<T>) manager.SelectAll(eagerlyLoading);
        }

        public void Insert<T>(T entity) where T : IEntity
        {
            var manager = new EntityProviderFactory(_context).GetForType<T>();
            manager.Insert(entity);
        }

        #endregion

        #region Queries

        public int GetStock(Product product)
        {
            var query = string.Format("SELECT SUM(Quantity) FROM Transactions WHERE (ProductId = {0})", product.Id);
            var resultSet = _context.Database.SqlQuery<int?>(query).ToList();
            var ret = resultSet.First();
            return ret ?? 0;
        }

        #endregion

        public void Dispose()
        {
            _context.Dispose();
        }
    }
}
